#include "StateManager.h"
#include "Overlord.h"

namespace XGE
{
    void StateManager::_loadNextState(void)
    {
        prevState = currState;
        currState = nextState;
        nextState = 0;

        currState->_onEnter();
    }

    //Manager initialisation
    bool StateManager::init(void)
    {
        if(nextState)
        {
            nextState->_onEnter();

            return true;
        }

        throw(Ogre::Exception(Ogre::Exception::ERR_INVALIDPARAMS, "Cannot initialize without a valid initial state!", "StateManager.cpp"));
    }

    //Update
    bool StateManager::_update(void)
    {
        if(XGE::Overlord::getSingletonPtr()->getWindow()->isClosed())
        {
            currState->_onExit();

            return true;
        }

        if(currState->_update())
        {
            currState->_onExit();

            if(nextState)
            {
                this->_loadNextState();
            }
            else
            {
                return true;
            }
        }

        Ogre::Root::getSingletonPtr()->renderOneFrame();

        return false;
    }

    //Set Next State
    bool StateManager::setNextState(const Ogre::String& nStateName)
    {
        if(elements[nStateName])
        {
            nextState = (XGE::State*)elements[nStateName];
            return true;
        }

        throw(Ogre::Exception(Ogre::Exception::ERR_ITEM_NOT_FOUND, "Could not set next state to \"" + nStateName + "\" because it is not a registered state!", "StateManager.cpp"));
        return false;
    }

    //Gets the name of the previous State
    Ogre::String StateManager::getPreviousState(void)
    {
        if(prevState)
        {
            return prevState->getName();
        }

        return 0;
    }

    //Gets the name of the current State
    Ogre::String StateManager::getCurrentState(void)
    {
        if(currState)
        {
            return currState->getName();
        }

        return 0;
    }

    //Gets the name of the next State
    Ogre::String StateManager::getNextState(void)
    {
        if(nextState)
        {
            return nextState->getName();
        }

        return 0;
    }

}
